import datetime
from datetime import timedelta
from datetime import datetime as dt
import os
import time

from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import Keys

from Case.python_ui.Common.basepage import Basepage
from Case.python_ui.PageLocate.admin_ticket_locator import AdminTicketLocator
from Case.python_ui.Pageobject.admin_notification_template_pages import AdminNotificationTemplatePage
from Case.python_ui.Test_data.menu_name_data import MenuName


class AdminTicketPages(Basepage):
    team_tickets_ticketNum = "F202403100011"
    overview_item_titles = ['Ticket Amount', 'Reopening Rate', 'Ticket Close Rate', 'Response Duration AVG.',
                            'Close Duration On Average', 'Processing Duration AVG']
    detail_columns = ['Support Member Name', 'Account Email', 'Support Team', 'Auto Assigned Ticket Amount',
                      'Manul Assigned Ticket Amount', 'Received Transferred Ticket Amount', 'Close Ticket Amount',
                      'Close Duration AVG (Min)',
                      'Online Duration (Hour)', 'Processing Duration AVG. - High Level (Min)',
                      'Processing Duration AVG. - Medium Level (Min)', 'Processing Duration AVG. -Low Level (Min)',
                      'NO. Of Reopening Tickets', 'Reopening Rate']

    query_param = {
        'time': {
            'start_time': '01-02-2024',
            'end_time': '29-02-2024'
        },

        'admin_email': 'lwm528675013@163.com',
        'sup_team': 'Financial Support',
        'no_result': 'wrong_keyword'
    }

    def element_is_exist(self, locate):
        doc = '判断元素是否存在'
        try:
            self.get_element(locate, doc)
        except NoSuchElementException as e:
            return False
        else:
            return True

    def enter_team_tickets(self):
        doc = "进入Team Tickets页面"
        time.sleep(2)
        self.wait_elevisble(AdminTicketLocator.dashboard_tab, doc)
        self.click_element(AdminTicketLocator.dashboard_tab, doc)
        time.sleep(1)
        self.wait_elevisble(AdminTicketLocator.bill_tab, doc)
        self.click_element(AdminTicketLocator.bill_tab, doc)
        time.sleep(1)
        self.wait_elevisble(AdminTicketLocator.team_tickets_tab, doc)
        self.click_element(AdminTicketLocator.team_tickets_tab, doc)
        time.sleep(3)

    def enter_tickets_report(self):
        doc = "进入Tickets Report页面"
        self.wait_elevisble(AdminTicketLocator.dashboard_tab, doc)
        self.click_element(AdminTicketLocator.dashboard_tab, doc)
        time.sleep(1)
        self.wait_elevisble(AdminTicketLocator.bill_tab, doc)
        self.click_element(AdminTicketLocator.bill_tab, doc)
        time.sleep(1)
        self.wait_elevisble(AdminTicketLocator.tickets_report_tab, doc)
        self.click_element(AdminTicketLocator.tickets_report_tab, doc)
        time.sleep(3)

    def admin_check_ticket_report(self):
        doc = "成员用户查看票据详细信息页面"
        self.enter_tickets_report()

        # 判断overview部分展示的内容
        title_list = self.get_elements(AdminTicketLocator.overview_item_titles, doc)

        time.sleep(3)
        index = 0
        for item in title_list:
            print(item.text)
            assert self.overview_item_titles[index] in item.text
            index += 1
            if index >= 4:
                self.move_mouse_to_element(AdminTicketLocator.slide)
                self.wait_elevisble(AdminTicketLocator.next_button, doc)
                self.click_element(AdminTicketLocator.next_button, doc)
                time.sleep(1)
                self.click_element(AdminTicketLocator.next_button, doc)
                continue
            else:
                continue

        # 判断detail部分展示的内容
        js = "document.getElementsByClassName('antd4-table-content')[0].scrollLeft=1000"
        self.excute_js(js)
        index = 0
        detail_columns_list = self.get_elements(AdminTicketLocator.detail_columns, doc)
        for column in detail_columns_list:
            assert self.detail_columns[index] in column.text
            index += 1

    def query_trigger(self, mode, start_time='01-02-2024', end_time='29-02-2024', keyword='', if_refresh=False):
        doc = "查询ticket report"
        if mode == "time":
            # 去除时间选择器的readonly属性
            js1 = "document.getElementById('date').removeAttribute('readonly')"
            js2 = "document.querySelector('input[readonly]').removeAttribute('readonly')"
            self.excute_js(js1)
            self.excute_js(js2)
            # 输入起止时间查询
            self.send_keys(AdminTicketLocator.start_time_input, Keys.CONTROL + "a", doc)
            self.send_keys(AdminTicketLocator.start_time_input, Keys.BACK_SPACE, doc)
            self.send_keys(AdminTicketLocator.start_time_input, start_time, doc)
            time.sleep(2)
            self.send_keys(AdminTicketLocator.end_time_input, Keys.CONTROL + "a", doc)
            self.send_keys(AdminTicketLocator.end_time_input, Keys.BACK_SPACE, doc)
            self.send_keys(AdminTicketLocator.end_time_input, end_time, doc)
            time.sleep(2)

        elif mode == "keyword":

            # 输入管理员邮箱/support team查询
            self.send_keys(AdminTicketLocator.name_input, keyword, doc)
            time.sleep(1)
            self.click_element(AdminTicketLocator.query_button, doc)
            time.sleep(2)
            if self.element_is_exist(AdminTicketLocator.empty_table) is False:
                assert self.assert_value(keyword, doc)

        if if_refresh:
            time.sleep(3)
            self.refresh_page()

    def assert_value(self, keyword, doc):
        email_list = self.get_elements(AdminTicketLocator.email_values, doc)
        team_list = self.get_elements(AdminTicketLocator.team_values, doc)
        if len(email_list) != 0:
            return keyword in [email.text for email in email_list] or keyword in [team.text for team in team_list]
        elif keyword == self.query_param["no_result"] and len(email_list) == 0:
            return True
        else:
            return False

    def query_ticket_report(self):
        self.enter_tickets_report()
        self.query_trigger("time", self.query_param['time']['start_time'], self.query_param['time']['end_time'],
                           if_refresh=True)
        time.sleep(3)
        self.query_trigger("keyword", keyword=self.query_param['admin_email'], if_refresh=True)
        time.sleep(3)
        self.query_trigger("keyword", keyword=self.query_param['sup_team'], if_refresh=True)
        time.sleep(3)
        self.query_trigger("keyword", keyword=self.query_param['no_result'])

    def download_report(self, cmdopt):
        doc = "下载ticket report"
        self.enter_tickets_report()
        time.sleep(3)
        self.query_trigger("time", self.query_param['time']['start_time'], self.query_param['time']['end_time'])
        time.sleep(3)
        self.click_by_js(AdminTicketLocator.download_ticket_report_button, doc)
        time.sleep(10)
        file_name = "TicketReport"
        list_of_files = os.listdir(MenuName.download_path[cmdopt])
        # list_of_files = os.listdir("C:\\Users\\qq178\\Downloads")
        latest_file = list_of_files[-1]
        assert latest_file.startswith(file_name) and latest_file.endswith(".pdf")

    def enter_notification_template_page(self):
        doc = "进入Export Records页面"
        js_object = 'document.getElementsByClassName("cre-sider-menu cre-sider-menu-open")[0].scrollTop=10000'
        self.excute_js(js_object)
        time.sleep(2)
        self.click_by_js(AdminTicketLocator.data_deletion_menu, doc)
        time.sleep(2)
        self.click_element(AdminTicketLocator.notification_template_tab, doc)
        time.sleep(5)

    def date_reverse(self, date_str: str):
        """ 倒置时间字符串 """
        data_str_list = date_str.split('-')
        data_str_list.reverse()
        return '-'.join(data_str_list)

    def notification_template_choose_sendtime(self):
        doc = "选择公告发送时间"
        self.enter_notification_template_page()

        self.click_element(AdminTicketLocator.template_active_send, doc)
        time.sleep(3)
        self.click_element(AdminTicketLocator.template_specific_send_time, doc)
        time.sleep(1)
        self.click_element(AdminTicketLocator.template_edit_confirm, doc)
        time.sleep(1)
        assert self.element_is_exist(AdminTicketLocator.template_empty_sendtime_alert)

        time.sleep(3)

        self.get_elements(AdminTicketLocator.template_specific_time_selector, doc)[0].click()
        time.sleep(1)
        self.click_element(AdminTicketLocator.template_specific_time_selector_today, doc)
        time.sleep(1)
        self.click_element(AdminTicketLocator.template_specific_time_selector_confirm, doc)
        time.sleep(2)
        current_date = datetime.date.today()
        expiration_date = dt.strptime(self.date_reverse(self.get_elements(AdminTicketLocator.template_specific_time_selector, doc)[1].get_attribute("title")[0:10]), "%Y-%m-%d").date()

        assert current_date + timedelta(days=7) == expiration_date


    def notification_template_send_history(self):
        doc = "查看通知模板发送历史"
        thead_list = ["Instance ID", "Notification Title", "Channel", "Receiver", "Estimated Sending Time", "Expired Time", "Actual Sending Time", "Status", "Actions"]
        self.enter_notification_template_page()
        if self.element_is_exist(AdminTicketLocator.template_name):
            self.click_element(AdminTicketLocator.template_name, doc)

            self.wait_elevisble(AdminTicketLocator.template_detail_send_history_tab, doc)
            self.click_element(AdminTicketLocator.template_detail_send_history_tab, doc)
            time.sleep(3)
            thead_items = [item.text for item in self.get_elements(AdminTicketLocator.thead_item, doc) if item.text != ""]
            for thead in thead_items:
                assert thead_list[thead_items.index(thead)] in thead





